package org.tinygroup.channel.protocol.impl;

import java.util.ArrayList;
import java.util.List;

import org.tinygroup.channel.protocol.ProtocolInInterface;
import org.tinygroup.channel.protocol.ProtocolInListener;
import org.tinygroup.context.Context;
import org.tinygroup.context.util.ContextFactory;

@SuppressWarnings({ "rawtypes", "unchecked" })
public abstract class AbstractProtocolIn<ProRequest, ProResponse> extends
		AbstractProtocol implements
		ProtocolInInterface<ProRequest, ProResponse> {
	private List<ProtocolInListener> listeners = new ArrayList<ProtocolInListener>();

	public List<ProtocolInListener> getListeners() {
		return listeners;
	}

	public void setListeners(List<ProtocolInListener> listeners) {
		this.listeners = listeners;
	}

	public void addProtocolListener(ProtocolInListener listener) {
		listeners.add(listener);
	}

	public ProResponse received(ProRequest proRequest) {
		Context context = ContextFactory.getContext();
		ProResponse proResponse = realDeal(proRequest, context);
		return proResponse;
	}

	protected abstract ProResponse realDeal(ProRequest proRequest,
			Context context);

	protected ProRequest afterReceived(ProRequest proRequest, Context context) {
		for (ProtocolInListener listener : listeners) {
			proRequest = (ProRequest) listener.afterReceived(proRequest,
					context);
		}
		return proRequest;
	}

	protected Object afterRequestToBizTrans(ProRequest proRequest,
			Object bizRequest, Context context) {
		for (ProtocolInListener listener : listeners) {
			bizRequest = listener.afterRequestToBizTrans(proRequest,
					bizRequest, context);
		}
		return bizRequest;
	}

	protected Object afterProcess(ProRequest request, Object bizResponse,
			Context context) {
		for (ProtocolInListener listener : listeners) {
			bizResponse = listener.afterProcess(request, bizResponse, context);
		}
		return bizResponse;
	}

	protected ProResponse afterBizToResponseTrans(Object bizResponse,
			ProResponse proResponse, Context context) {
		for (ProtocolInListener listener : listeners) {
			proResponse = (ProResponse) listener.afterBizToResponseTrans(
					bizResponse, proResponse, context);
		}
		return proResponse;
	}

}
